program write_tp_2km_ymonthly

  use flogger
  use mongof_common_mod
  use utils_mod

  implicit none

  character(30) mongo_uri
  character(30) mongo_db
  character(30) mongo_col
  character(256) grid_file_path
  character(256) t_file_path
  integer cid, nlon, nlat, nlev
  real(8), allocatable, dimension(:) :: lon, lat, lev
  real(8), allocatable, dimension(:,:,:,:) :: t
  real(8), allocatable, dimension(:,:,:) :: t2

  integer i, j, k

  interface
    integer function write_data_zlev(cid, nlon, nlat, t2) result(res) bind(c, name='write_data_zlev')
      use iso_c_binding
      integer(c_int), intent(in), value :: cid
      integer(c_int), intent(in), value :: nlon
      integer(c_int), intent(in), value :: nlat
      real(c_double), intent(in) :: t2(12,nlon,nlat)
    end function write_data_zlev
  end interface

  call get_command_argument(1, mongo_uri)
  call get_command_argument(2, t_file_path)

  mongo_uri = 'mongodb://' // trim(mongo_uri) // char(0)
  mongo_db = 'hntp' // char(0)
  mongo_col = 'tp_2km_ymonthly' // char(0)

  call handle_mongo_error(mongoc_connect(mongo_uri, mongo_db, mongo_col, cid), __FILE__, __LINE__)
  call handle_mongo_error(mongoc_create_data_index(cid), __FILE__, __LINE__)

  call read_grid(t_file_path, nlon, nlat, nlev, lon, lat, lev)

  allocate(t(nlon,nlat,nlev,12))
  allocate(t2(12,nlon,nlat))

  call read_data_4d(t_file_path, 't_ave', t)

  do j = 1, nlat
    do i = 1, nlon
      t2(:,i,j) = t(i,j,1,:)
    end do
  end do

  call log_notice('Start to write database.')
  call handle_mongo_error(write_data_zlev(cid, nlon, nlat, t2), __FILE__, __LINE__)
  call mongoc_final()

  deallocate(lon, lat, lev, t, t2)

end program write_tp_2km_ymonthly
